﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebApiV2.Data;

namespace WebApiV2.Domain
{
    public class EfResponsitory<T> : IResponsitory<T> where T : BaseEntity
    {
        

        private readonly Admin3400DbContext db;
        public EfResponsitory(Admin3400DbContext admin)
        {
            db = admin;
        }

        private DbSet<T> _entity;

        protected DbSet<T> Entity  //可查询的
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }
        
        public IQueryable<T> Table 
        { get 
            {
                return Entity;
            }
        }
        public void Delete(int Id)
        {
            var row = Table.Where(x => x.Id == Id).FirstOrDefault();
            Delete(row);
        }

        public void Delete(T entity)
        {
            this._entity.Remove(entity); //把Table换成entity

            db.SaveChanges(); //保存更改
        }
        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entities)
        {
            Entity.RemoveRange(entities);
            db.SaveChanges();
        }

    }
}
